<template>
    <view>
        <view class="p_20">
            <view class="dis_f_r_c m_b_10">
                <view class="release dis_f_c_c" @click="handleSend">发布</view>
            </view>
            <view class="content_box">
<!--                <u&#45;&#45;textarea v-model="query.bt"  autoHeight  border="none" placeholder="职位名称" ></u&#45;&#45;textarea>-->
                <u--textarea v-if="type==2" v-model="query.nr" border="none" placeholder="内容描述..." ></u--textarea>
                <view @click="handleUploadClick" v-if="type==2">
                    <u-upload
                        :fileList="fileList1"
                        @afterRead="afterRead"
                        @delete="deletePic"
                        capture="album"
                        name="1"
                        multiple
                        :maxCount="9"
                        @oversize="oversize"
                    ></u-upload>
                    <view style="font-size: 24rpx;color: #666666">请上传图片</view>
                </view>
                <view class="m_t_10">
                    <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
                    <u--form
                        labelPosition="left"
                        :model="query"
                        :rules="rules"
                        ref="uForm"
                        labelWidth="100"
                    >
                        <u-form-item
                            v-if="type==1"
                            label="企业名称"
                            prop="enterpriseName"
                            borderBottom
                            ref="item1"
                            required
                        >
                            <u--input
                                v-model="query.enterpriseName"
                                border="none"
                                placeholder="请输入企业名称"
                            ></u--input>
                        </u-form-item>
                        <u-form-item
                            label="职位名称"
                            prop="bt"
                            borderBottom
                            ref="item1"
                            required
                        >
                            <u--input
                                v-model="query.bt"
                                border="none"
                                placeholder="请输入职位名称"
                            ></u--input>
                        </u-form-item>
                        <u-form-item
                            v-if="type==1"
                            label="职位描述"
                            prop="nr"
                            borderBottom
                            ref="item1"
                            required
                        >
                            <u--textarea
                                v-model="query.nr"
                                border="none"
                                placeholder="请输入职位描述"
                                autoHeight
                            ></u--textarea>
                        </u-form-item>
                        <u-form-item
                            label="职位类别"
                            prop="lxNameEj"
                            borderBottom
                            ref="item1"
                            required
                        >
                            <uni-data-picker v-model="query.lxNameEj"  :localdata="pickerTypeList" placeholder="请选择职位类别" popup-title="请选择职位类别" @change="onTypeChange" ></uni-data-picker>
                        </u-form-item>
                        <u-form-item
                            label="薪资范围"
                            prop="money"
                            borderBottom
                            ref="item1"
                            required
                        >
                            <u--input
                                v-model="query.money"
                                border="none"
                                :placeholder="type==1?'请输入薪资范围':'请输入期望薪资'"
                            ></u--input>
                        </u-form-item>
                        <u-form-item
                            label="学历"
                            prop="education"
                            borderBottom
                            ref="item1"
                            required
                        >
                            <u--input
                                v-model="query.education"
                                border="none"
                                placeholder="请输入学历"
                            ></u--input>
                        </u-form-item>
                            <u-form-item
                                label="工作经验(年)"
                                prop="jobBenefits"
                                borderBottom
                                ref="item1"
                                required
                            >
                                <u--input
                                    v-model="query.jobBenefits"
                                    border="none"
                                    placeholder="请输入几年工作经验"
                                ></u--input>
                            </u-form-item>
                        <u-form-item
                            v-if="type==1"
                            label="职位福利"
                            prop="workExperience"
                            borderBottom
                            ref="item1"
                        >
                            <u--textarea
                                v-model="query.workExperience"
                                border="none"
                                placeholder="请输入职位福利"
                                autoHeight
                            ></u--textarea>
                        </u-form-item>
                        <u-form-item
                            label="联系人"
                            prop="lxrXm"
                            borderBottom
                            ref="item1"
                            required
                        >
                            <u--input
                                v-model="query.lxrXm"
                                border="none"
                                placeholder="请输入联系人"
                            ></u--input>
                        </u-form-item>
                        <u-form-item
                            label="联系电话"
                            prop="lxrDh"
                            borderBottom
                            ref="item1"
                            required
                        >
                            <u--input
                                v-model="query.lxrDh"
                                border="none"
                                placeholder="请输入联系电话"
                            ></u--input>
                        </u-form-item>
                        <view v-if="type==2">
                            <u-form-item
                                label="性别"
                                prop="sex"
                                borderBottom
                                @click="showSex = true"
                                ref="item1"
                                required
                            >
                                <u--input
                                    v-model="query.sex"
                                    disabled
                                    disabledColor="#ffffff"
                                    placeholder="请选择性别"
                                    border="none"
                                ></u--input>
                                <u-icon
                                    slot="right"
                                    name="arrow-right"
                                ></u-icon>
                            </u-form-item>
                        <u-form-item
                            label="年龄"
                            prop="age"
                            borderBottom
                            ref="item1"
                            required
                        >
                            <u--input
                                v-model="query.age"
                                border="none"
                                placeholder="请输入年龄"
                            ></u--input>
                        </u-form-item>
                        </view>
<!--                        <u-form-item-->
<!--                            label="身份"-->
<!--                            prop="sf"-->
<!--                            borderBottom-->
<!--                            ref="item1"-->
<!--                        >-->
<!--                            <u-radio-group v-model="query.sf">-->
<!--                                <u-radio shape="circle" value="个人" name="个人" label="个人" ></u-radio>-->
<!--                                <view class="m_l_10">-->
<!--                                    <u-radio shape="circle" value="企业" name="企业" label="企业" ></u-radio>-->
<!--                                </view>-->
<!--                            </u-radio-group>-->
<!--                        </u-form-item>-->
                        <u-form-item
                            label="地址"
                            prop="quantity"
                            borderBottom
                            ref="item1"
                            required
                        >
<!--                            <view class="dis_f_r_c">
                                <view>
                                    <u-button @click="handleMap" size="small" type="primary">获取位置</u-button>
                                </view>
                            </view>-->
                            <uni-data-picker v-model="query.districts" :localdata="areaList" placeholder="请选择地区" popup-title="请选择地区" @change="onchange"  ></uni-data-picker>
                        </u-form-item>
<!--                        <view class="dis_f_r_c m_t_10 m_b_10 f_s_14 c_9">{{query.dz}}</view>-->
                        <u-form-item
                            label="详细地址"
                            prop="locationsName"
                            borderBottom
                            ref="item1"
                        >
                            <u--textarea
                                v-model="query.locationsName"
                                border="none"
                                autoHeight
                                placeholder="请输入详细地址"
                            ></u--textarea >
                            <view slot="right" class="c_green" @click="handleMap">获取位置</view>
                        </u-form-item>
<!--                        <u-form-item
                            label="是否匿名发布"
                            borderBottom
                            ref="item1"
                        >
                            <u-radio-group v-model="query.sfnm">
                                <u-radio shape="circle" value="1" name="1" label="不匿名" ></u-radio>
                                <view class="m_l_10">
                                    <u-radio shape="circle" value="2" name="2" label="匿名" ></u-radio>
                                </view>
                            </u-radio-group>
                        </u-form-item>-->
                    </u--form>
                </view>
                <view>
                    <!--                    <view class="line_title m_t_20">发布要求</view>-->
                    <u-divider text="发布要求"></u-divider>
                    <view class="f_s_14 m_t_10 c_9">{{sendAsk}}</view>
                </view>
            </view>
            <u-picker :show="showPicker"
                      :columns="columnsPicker"
                      :keyName="keyName"
                      @cancel="showPicker = false"
                      @confirm="handlePickerShure"></u-picker>
        </view>
        <u-action-sheet
            :show="showSex"
            :actions="actions"
            title="请选择性别"
            @close="showSex = false"
            @select="sexSelect"
        >
        </u-action-sheet>
        <u-modal :show="showTips" title="提示" confirmText="开通会员" cancelText="支付" :showCancelButton="true" @confirm="handleConfirm" @cancel="handleCancel">
         <view>单条发布需支付{{money}}元</view>
        </u-modal>
        <!-- 授权弹窗 -->
        <s-auth-modal />
    </view>
</template>
<script>

import {baseUrl} from "@/sheep/request/baseUrl";
import {getByKeyApi, addInformationApi, getAddressApi, getAreaListApi, topUpApi,getMyInfoApi } from "@/sheep/api";
export default {
    name: "index",
    data() {
        return {
            accept:'',
            pickerTypeList:[],
            sendAsk:'',
            columnsPicker:[],
            showPicker: false,
            keyName:'',
            fileListImg: [],
            showSex: false,
            actions: [{
                name: '男',
            },
                {
                    name: '女',
                }],
            fileList1: [],
            fileList2: [],
            className: null,
            isRecharge: false,
            payNum: null,
            formData: {
                user: 'test'
            },
            areaList:[],
            query: {
                enterpriseName: '',
                bt: '',
                nr: '',
                province: '',
                city: '',
                districts: '',
                lxrXm: '',
                lxrDh: '',
                sf: '',
                locationsName: '',
                money: '',
                education: '',
                jobBenefits: '',
                workExperience: '',
                sex: '',
                age: '',
                sfnm: '1',
                // lot:'',
                // lat:'',
            },
            rules: {
                'enterpriseName': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'bt': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'nr': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'money': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'lxrXm': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'lxrDh': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'education': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'jobBenefits': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'sex': {
                    type: 'string',
                    required: true,
                    message: '请选择',
                    trigger: ['blur', 'change']
                },
                'age': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'lxNameEj': {
                    type: 'string',
                    required: true,
                    message: '请选择',
                    trigger: ['blur', 'change']
                },
                'sf': {
                    type: 'string',
                    required: true,
                    message: '请选择',
                    trigger: ['blur', 'change']
                },
            },

            isShow: false,
            type:'',
            classList:[],
            queryData:'',
            listId:'',
            queryName:'',
            vipRules:'',
            topUpForm: {
                payWay: "WX_XCX_PAY",
                amount: "",
                attach: "",
                orderType: "purchase",
                desc: "单条信息发布",
            },
            money:'',
            showTips:false,
        }
    },
    onLoad(params) {
        this.type=params.type
        this.query.type=params.type
        if (this.type==1){
            this.accept ='media'
        }else{
            this.accept ='file'
        }
        //设置顶部标题
        uni.setNavigationBarTitle({
            title: this.type==1?'我要招聘':'我要求职'
        })
    },
    onShow() {
        if (!this.isShow) {
            // this.handleReset()
        }
        this.getSendAsk()
        this.getClassList()
        this.getArea()
        this.getTypeList()
        this.getMoney()
        // this.getImg()
        // this.isRecharge = false
        // this.getTagAllList()
        // this.getClassData()
    },
    methods: {
        async getSendAsk() {
            let res = await getByKeyApi("fbyq");
            this.sendAsk = res.data[0]?.configValue;
        },
        async getMoney() {
            let res = await getByKeyApi("money");
            this.money = res.data[0]?.configValue;
            this.topUpForm.amount = this.money
        },
        async getClassList() {
            let res = await getByKeyApi("cpfl");
            this.classList = [res.data]||[]
        },
        async getTypeList() {
            let res = await getByKeyApi("goods_type");
            this.pickerTypeList = res.data.map(item=>{
                let children=[]
                if (item.remark){
                    let s1 = item.remark.split('-')
                    children=s1.map(sItem=>{
                        return {
                            text: sItem,
                            value: sItem
                        }
                    })
                }
                return {
                    text: item.configName,
                    value: item.configName,
                    children:children
                }
            })
        },
        sexSelect(e) {
            this.query.sex = e.name
            this.$refs.uForm.validateField('query.sex')
        },
        onchange(e) {
            console.log("e", e.detail.value);
            const value = e.detail.value
            if (value.length>0){
                this.query.province= value[0].text
                this.query.city= value[1].text
                this.query.districts= value[2].text
            }else{
                this.query.province = ''
                this.query.city = ''
                this.query.districts = ''
            }
        },
        getArea(){
            getAreaListApi().then(res=>{
                this.areaList = this.filterAreaName(res.data)
            })
        },
        filterAreaName(data){
            // if(!(data?.length <= 0)){
            // 等价于
            if(!data || data.length <= 0){ // 递归的出口
                return null;
            }
            return data.map(x => { // 循环数据
                const model = { // 把后端返回过来的数据里面的键给替换成我想要的键
                    children: x.children,
                    text: x.name,
                    value: x.areaCode,
                };
                const children = this.filterAreaName(x.children); // 子级数据

                if(children){ // 一直往下循环查找有没有children这个键，如果有就直接添加一个子级字段名，这个字段名就是存子级数据
                    model.children = children;
                }
                return model; // 返回这个数据
            })
        },
        onTypeChange(e){
            const value = e.detail.value
            console.log("value", value);
            if (value.length>0){
                this.query.lxNameYj = value[0].text
                this.query.lxNameEj = value[1].text
            }else{
                this.query.lxNameYj = ''
                this.query.lxNameEj = ''
            }

        },
        // 文件超出大小限制
        oversize() {
            uni.showToast({
                title: "上传最大不能超过20M",
                icon: 'none'
            })
        },

        // 选择收货地址
        handleMap() {
            let that = this;
            uni.showLoading({ title: "获取位置中" });
            uni.getLocation({
                type: "gcj02", //返回可以用于uni.openLocation的经纬度
                success: function (res) {
                    const latitude = res.latitude;
                    const longitude = res.longitude;
                    getAddressApi({ location: latitude + "," + longitude }).then((res) => {
                            that.query.locationsName = res.data;
                            uni.hideLoading();
                        }
                    );
                },
                fail: function (err) {
                    uni.hideLoading();
                    uni.showToast({
                        title: "获取位置失败",
                        icon: "none"
                    });
                }
            });
        },
        handleShowPicker(queryName,queryData,listId,list,keyName){
            /**
             * queryName 双向绑定的name,queryData 传给后端的字段名，listId picker的id,list picker的列表，keyName picker的keyName
             * */
            this.queryData = queryData
            this.queryName = queryName
            this.listId = listId
            this.columnsPicker = this[list]
            this.keyName = keyName
            this.showPicker = true
        },
        handlePickerShure(e){
            this.query[this.queryData] =  e.value[0][this.listId]
            this.query[this.queryName] =  e.value[0][this.keyName]
            this.showPicker = false
        },
        handleReset() {
            this.query = {
                productType:this.type,
                advertTitle: '',
                productImg: '',
                className: '',
                classId: '',
                lxNameEj: '',
                quantity: '',
                unit: '',
                price: '',
                priceType: '',
                receiveAddress: '',
                address: '',
                receiveTime: '',
            }
            this.fileList1 = []
            this.fileList2 = []
        },

        confirm(e) {
            this.query.receiveAddress = e.value[0].name + e.value[1].name + e.value[2].name
            this.showAddress = false
        },
        //开通会员
        handleConfirm(){
            this.showTips=false
            uni.navigateTo({
                url: "/pages/mine/vipList",
            });
        },
        //单条支付
        handleCancel() {
            this.handleToVip()
        },

        handleSend() {
            this.$refs.uForm.validate().then(res=>{
                if (this.type==2){
                    if (Array.isArray(this.fileList1)) {
                        if (this.fileList1.length > 0) {
                            this.fileList1.forEach((item, index) => {
                                if (index === 0) {
                                    this.query.photo = item.ossId;
                                } else {
                                    this.query.photo = this.query.photo + "," + item.ossId;
                                }
                            });
                        } else {
                            this.query.photo = "";
                        }
                    }
                    if (!this.query.nr){
                        uni.showToast({
                            title:'请填写内容',
                            icon: 'none'
                        })
                        return
                    }
                }
                if (this.type==1){
                    getMyInfoApi().then((res) => {
                        if (res.data.hyNumber>0){
                            this.send()
                        }else{
                            //单条支付还是充会员
                            this.showTips=true
                        }
                    });

                }else{
                    this.send()
                }
                this.send()

            })
        },
        send(){
            uni.showLoading({});
            addInformationApi(this.query).then(res => {
                uni.hideLoading()
                uni.showToast({
                    title: res.msg,
                    icon: 'none'
                })
                if (res.code == 200){
                    let that =this
                    //关闭当前页面 跳到我的发布页面
                    setTimeout(() => {
                        if (that.type==1){
                            uni.redirectTo({
                                url: '/pages/mine/mySend',
                            })
                        }else{
                            uni.redirectTo({
                                url: 'pages/mine/mySendApply',
                            })
                        }

                    }, 1000);
                }
            })
        },
        handleToVip(){
            topUpApi(this.topUpForm).then(
                ({ data }) => {
                    let that = this;
                    uni.requestPayment({
                        provider: "wxpay",
                        timeStamp: data.timeStamp,
                        nonceStr: data.nonceStr,
                        package: data.packageValue,
                        signType: data.signType,
                        paySign: data.paySign,
                        success: function(res) {
                            uni.showToast({
                                title: '支付成功',
                                icon: 'none',
                                duration: 2000
                            })
                            that.send()
                        },
                        fail: function(err) {},
                    });
                });
        },
        handleUploadClick() {
            this.isShow = true
        },
        // 上传图片
        async afterRead(event) {
            let lists = [].concat(event.file);
            console.log("lists", lists);
            console.log(" this[`fileList${event.name}`]",  this[`fileList${event.name}`]);
            let fileListLen = this[`fileList${event.name}`].length;
            console.log("fileListLen", fileListLen);
            lists.map((item, index) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url, lists, event);
                console.log("result", result);
                let item = this[`fileList${event.name}`][fileListLen];
                this[`fileList${event.name}`].splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        url: result.url,
                        name: result.fileName,
                        ossId: result.ossId
                    })
                );
                fileListLen++;
            }
        },
        uploadFilePromise(url, lists, event) {
            let token = uni.getStorageSync('token')
            let headerToken = "Bearer " + token
            return new Promise((resolve, reject) => {
                let a = uni.uploadFile({
                    url: baseUrl + "/resource/oss/upload",
                    filePath: url,
                    name: "file",
                    header: {
                        Authorization: headerToken,
                        clientId: "be7052a7e4f802c20df10a8d131adb12"
                    },
                    formData: {
                        user: "test",
                    },
                    success: (res) => {
                        let data = JSON.parse(res.data);
                        console.log("data", data);
                        if (data.code == 200) {
                            resolve(data.data);
                        } else {
                            if (lists.length > 0) {
                                lists.map((item, index) => {
                                    this[`fileList${event.name}`].splice(index, 1)
                                });
                            }
                            uni.showToast({
                                title: data.msg,
                                icon: "none",
                            });
                        }
                    },
                });
            });
        },
        // 删除图片
        deletePic(event) {
            this[`fileList${event.name}`].splice(event.index, 1);
        },
    }
}
</script>

<style scoped lang="scss">
.release {
    width: 100rpx;
    height: 70rpx;
    font-size: 28rpx;
    border-radius: 10rpx;
    background-color: #3c9cff;
    color: #ffffff;
}

// 支付弹层
.pay {
    padding: 30rpx;

    .pay-title {
        font-size: 35rpx;
    }

    .pay-select {
        margin: 50rpx;
    }

    .pay-flex {
        display: flex;
        margin-top: 30rpx;

        /deep/ .u-button {
            height: 84rpx !important;
            font-size: 30rpx;

            &:first-child {
                margin-right: 25rpx !important;
            }
        }
    }

    .surplus {
        margin-top: 35rpx;
        font-size: 25rpx;

        .surplus-num {
            margin-left: 15rpx;
        }
    }
}
</style>
